package com.kl.reconnect;

import com.kl.decodeandencode.MyMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 只要客户端上线就会触发该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "上线了 " + sdf.format(new Date()));
        channelGroup.add(channel);
        System.out.println(channel.remoteAddress() + "上线了 " + sdf.format(new Date()));
    }

    /**
     * 只要客户端下线就会触发该方法
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "下线了 " + sdf.format(new Date()));
        System.out.println(channel.remoteAddress() + "下线了 " + sdf.format(new Date()));
        System.out.println("当前在线客户端: " + channelGroup.size());
    }

    /**
     * 读取客户端发送的数据
     *
     * @param ctx 上下文对象, 含有通道channel，管道pipeline
     * @param msg 就是客户端发送的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器感知消息===");
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (ch == channel) {
                ch.writeAndFlush("[自己]" + ": " + msg);
            } else {
                ch.writeAndFlush("[客户端]" + ": " + msg);
            }
            System.out.println("[客户端]server" + ": " + msg);
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    }
}
